package com.lhd.usermanagement.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.lhd.usermanagement.common.BaseResponse;
import com.lhd.usermanagement.common.BaseResultUtils;
import com.lhd.usermanagement.common.ErrorCode;
import com.lhd.usermanagement.exception.BusinessException;
import com.lhd.usermanagement.model.domain.User;
import com.lhd.usermanagement.model.domain.request.UserLoginRequest;
import com.lhd.usermanagement.model.domain.request.UserRegisterRequest;
import com.lhd.usermanagement.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.lhd.usermanagement.constant.UserConstant.ADMIN_USER_ROLE;
import static com.lhd.usermanagement.constant.UserConstant.USER_LOGIN_STATE;

@RestController
@RequestMapping("/user")
@Slf4j
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/register")
    public BaseResponse<Long> register(@RequestBody UserRegisterRequest userRegisterRequest){
        log.info("userRegisterRequest:{}", userRegisterRequest);
        // 验证传过来的对象是否为空
        if (userRegisterRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求的对象不能为空");
        }

        String userAccount = userRegisterRequest.getUserAccount();
        String userPassword = userRegisterRequest.getUserPassword();
        String checkPassword = userRegisterRequest.getCheckPassword();
        String planetCode = userRegisterRequest.getPlanetCode();
        //校验4个数据是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword, checkPassword,planetCode)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"请求的参数不能为空");
        }
        long result = userService.userRegister(userAccount, userPassword, checkPassword, planetCode);
        return BaseResultUtils.success(result);
    }

    @PostMapping("/login")
    public BaseResponse<User> login(@RequestBody UserLoginRequest userLoginRequest, HttpServletRequest httpServletRequest){
        // 验证传过来的对象是否为空
        if (userLoginRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求的对象不能为空");
        }

        String userAccount = userLoginRequest.getUserAccount();
        String userPassword = userLoginRequest.getUserPassword();

        //检查账号和密码是否为空
        if (StringUtils.isAnyBlank(userAccount, userPassword)){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"账号或密码为空");
        }

        User user = userService.userLogin(userAccount, userPassword, httpServletRequest);
        return BaseResultUtils.success(user);
    }

    /**
     * 用户注销
     * @param httpServletRequest
     * @return
     */
    @PostMapping("/logout")
    public BaseResponse<Integer> loginOut( HttpServletRequest httpServletRequest){
        // 验证传过来的对象是否为空
        if (httpServletRequest == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求的对象不能为空");
        }

        int result = userService.userLoginOut(httpServletRequest);
        return BaseResultUtils.success(result);
    }

    @GetMapping("/current")
    public BaseResponse<User> getCurrentUser(HttpServletRequest request){
        Object userOnj = request.getSession().getAttribute(USER_LOGIN_STATE);
        User currentuser = (User) userOnj;
        if (currentuser == null){
            throw new BusinessException(ErrorCode.NULL_ERROR,"请求的对象不能为空");
        }
        long currentUserId = currentuser.getId();
        // todo 校验用户是否合法
        User user = userService.getById(currentUserId);
        // 返回脱敏的用户信息
        User safetyUser = userService.getSafetyUser(user);

        return BaseResultUtils.success(safetyUser);
    }

    @GetMapping("/search")
    public BaseResponse<List<User>> searchUsers(String username, HttpServletRequest request){
        // 管理员可查询
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"没有查询权限");
        }
        // 利用Mybatis-plus动态条件查询QueryWrapper的函数
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(username)){
            queryWrapper.like("username", username);
        }

        List<User> users = userService.list(queryWrapper);
        //对users集合中的每个User对象调用userService的getSafetyUser方法，获取对应的“安全用户”。
        //将这些“安全用户”放入一个新的List中并返回
        //返回一个脱敏后的List<user>
        List<User> userList = users.stream().map(user -> userService.getSafetyUser(user)).collect(Collectors.toList());

        //返回查询的列表
        return BaseResultUtils.success(userList);
    }

    /**
     * 通过 POST 请求删除用户。
     * 路径：/delete
     *
     * @param id 用户的ID，需要通过请求体传递。
     * @param request HttpServletRequest对象，用于获取请求信息。
     * @return boolean 返回删除操作是否成功。成功返回true，失败返回false。
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteUser(@RequestBody long id, HttpServletRequest request){
        // 判断请求者是否为管理员
        if (!isAdmin(request)){
            throw new BusinessException(ErrorCode.NO_AUTH,"没有查询权限");
        }
        // 校验用户ID是否合法（大于0）
        if (id <= 0){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"删除用户的id不合法");
        }
        // 执行删除操作，并返回结果
        boolean result = userService.removeById(id);
        return BaseResultUtils.success(result);

    }


    /**
     * 检查当前用户是否为管理员角色。
     * 该方法通过获取HttpSession中的用户登录状态来判断用户是否登录，并且登录的用户角色是否为管理员。
     *
     * @param request HttpServletRequest对象，用于获取当前请求的会话信息。
     * @return boolean 返回true表示用户是管理员角色，否则返回false。
     */
    public boolean isAdmin(HttpServletRequest request){
        // 从会话中获取登录的用户对象
        Object userObject = request.getSession().getAttribute(USER_LOGIN_STATE);
        User user = (User) userObject;

        // 判断用户对象不为空且用户角色为管理员
        return user != null && Objects.equals(user.getUserRole(), ADMIN_USER_ROLE);

    }


}
